<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\common\LoginType;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use app\model\UserToken;

class PasswordLogin
{
    use InstanceTrait;

    /**
     * 账号密码登录
     *
     * @param int    $mobile
     * @param string $password
     * @return array
     */
    public function passwordLogin(int $mobile, string $password): array
    {
        $where[] = ['mobile', '=', $mobile];
        $field   = 'id,mobile,status,create_time,avatar,login_type,ref,password';
        $user    = UserModel::where($where)->field($field)->find();
        if (empty($user)) return ['code' => 400, 'msg' => '用户不存在'];

        //密码加密 md5(md5(12345).id)
        $md5Password = md5($password . $user['id']);
        if ($md5Password != $user['password']) return ['code' => 400, 'msg' => '密码错误'];

        $userStatus = true;
        if ($user['status'] != 1) $userStatus = false;
        $param = [
            'uid'         => $user['id'],
            'type'        => 2,
            'user_status' => $userStatus ? 1 : 2,
            'status'      => $userStatus ? 1 : 2,
            'login_type'  => LoginType::LOGIN_TYPE_PHONE->value
        ];
        UserBehaviorLog::log($param);
        if (!$userStatus) return ['code' => 400, 'msg' => '当前账号状态异常，请联系管理员'];

        $token         = UserToken::loginToken($user, LoginType::LOGIN_TYPE_PHONE->value);
        $data['token'] = $token['token'] ?? '';

        $uid         = $user['id'];
        $data['uid'] = $uid;

        return ['code' => 200, 'msg' => '', 'data' => $data];
    }
}
